package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    private Configuration configuration;
    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    private String prefix;   //静态页面上传的 文件目录
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    AuthorMapper authorMapper;


    /**
     * 生成静态页面
     * @param content
     * @param apArticle
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        //获取文章内容
        try {
            //2. 模板  读取的是resources 下的article.ftl文件
            Template template = configuration.getTemplate("article.ftl");

            //3.数据
            Map<String,Object> map = new HashMap<>();
            map.put("content",JSONArray.parseArray(content));//文章的详情\
            map.put("article", apArticle);// 文章信息
            // 根据文章中的作者id 获取到文章作者的信息
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId",apAuthor.getUserId()); //将作者的id保存进map中

            StringWriter writer = new StringWriter();// 这是一个流对象 将内容写入到内存缓冲区中
            template.process(map,writer);

            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());

            //生成页面把html文件上传到minio中
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);

            //修改ap_article表 保存static_url字段
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);

            log.info("文章详情静态页 生成 成功 staticUrl为:{}",readPath+path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章静态页面生成失败=====> 文章id{} ====>原因{}",apArticle.getId(),e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文章静态页面生成失败");
        }
    }
}
